<template>
	<view class="content-img">
		<view class="header-content flex justify-content-space-between" :style="{paddingTop: statusBarHeight+'px'}">
			<view style="width: 100rpx;" @click="onTapLeft"><eui-uicons color="#000" type="back" size="40" /></view>
			<view class="flex align-items-center" style="font-size: 36rpx;font-weight: 600;" @click="TypeChange">
				{{selType}}<eui-uicons color="#222" :type="isTypeShow?'up':'down'" size="36" />
			</view>
			<view class="flex justify-content-flex-end" style=" padding-right: 30rpx;width: 100rpx;"></view>
		</view>
		<view class="email-option" :style="{top:(statusBarHeight+42)+'px'}" v-show="isTypeShow">
			<view class="flex padding-left-28 font-size-28" style="height: 88rpx;" @click="TypeEMailsQuery('收件箱')">
				<view
					class="flex flex-1 justify-content-space-between align-items-center border-bottom-eee padding-right-28">
					<view>收件箱</view>
					<view><eui-uicons :color="themeColor" type="checkmarkempty" size="44"
							v-if="selType=='收件箱'" /></view>
				</view>
			</view>
			<view class="flex padding-left-28 font-size-28" style="height: 88rpx;" @click="TypeEMailsQuery('发件箱')">
				<view class="flex flex-1 justify-content-space-between align-items-center padding-right-28">
					<view>发件箱</view>
					<view><eui-uicons :color="themeColor" type="checkmarkempty" size="44"
							v-if="selType=='发件箱'" /></view>
				</view>
			</view>
		</view>
		<view class="email-mask" v-show="isTypeShow" @click="TypeChange"></view>
		<eui-search-bar ref="approveSearch" v-model="searchValue" @confirm="selStoreById" radius="100"
			placeholder="搜索标题" showFilter>
			<template #searchFields>
				<view class="search-fields">
					<view class="center">
						<!-- <eui-card-input v-model="selectTime" :modelValue="selectTime" title="日期" :range="timeList"
							type="radio" alignType="left" @buttonClick="buttonClickTime" />
						<view class="flex date-defined" v-if="selectTime=='自定义'">
							<view class="flex-1"><eui-datetime-picker type="day" v-model="StartDt"
									placeholder="开始日期"></eui-datetime-picker></view>
							<view>-</view>
							<view class="flex-1"><eui-datetime-picker type="day" v-model="EndDt"
									placeholder="结束日期"></eui-datetime-picker></view>
						</view> -->
						<DateCard v-model="selectTime" :modelValue="selectTime" title="日期" type="date" :range="timeList"
							@buttonClick="buttonClickTime"></DateCard>
					</view>
					<view class="bottom flex-1 flex">
						<view class="flex-1 flex" style="padding-right: 7.5px;" @click="CancelCondition">
							<view class="flex-1 flex justify-content-center align-items-center bottom-bg"
								style="border: solid 1rpx rgba(136, 136, 136, 1);font-size: 15px;">重置</view>
						</view>
						<view class="flex-1 flex justify-content-center align-items-center" style="padding-left: 7.5px;"
							@click="ConfirmCondition">
							<view class="flex-1 flex justify-content-center align-items-center bottom-bg button-theme" :class="[theme]"
								style="color: #fff;font-size: 15px;">
								确认</view>
						</view>
						<!-- <eui-button type="max2" title="重置" @click="CancelCondition"></eui-button>
						<eui-button type="max" title="确认" @click="ConfirmCondition"></eui-button> -->
					</view>
				</view>
			</template>
		</eui-search-bar>
		<eui-tab :tabs="selType=='收件箱'?tabData:tabData2" :value="industryTabIndex" @change="tabChange" :tabStyle="tabStyle"></eui-tab>
	</view>
	<view class="main-view">
		<scroll-view scroll-y lower-threshold='88' @refresherrefresh="onRefresh" @scrolltolower="templateLower"
			:refresher-enabled='true' :refresher-triggered="triggered" :style="{width:scrollWidth,height:scrollHeight}">
			<EmailList :data="dataList" @change="onRefresh"></EmailList>
			<view v-if="dataList.length == 0" class="no-data flex flex-direction-column" style="background-color: RGBA(255,255,255,0);">
				<image src="@/static/img/no_data.png" mode="aspectFit" class="image" />
				<view class="color-888 font-size-28">暂无数据</view>
			</view>
		</scroll-view>
	</view>
	<view class="flex justify-content-center align-items-center email-edit" :class="[theme]" @click="openWriteEmail">
		<view class="iconfont icon-bianji" style="color: #fff;"></view>
	</view>
</template>

<script setup type="ts">
	import { ref } from 'vue';
	import { onLoad,onReady } from '@dcloudio/uni-app';
	import service from '@/common/service';
	import Enjoy from '@/common/enjoy';
	import dateRangUtil from '@/common/dateRangUtil';
	import { storeToRefs } from 'pinia';
	import { useMainStore } from '@/store/modules/store';
	import { useLoginStore } from '@/store/modules/useLoginStore';
	import { useThemeStore } from '../../../store/themeStore';
	import DateCard from "@/components/DateCard/index"
	import EmailList from './EmailList.vue';
	const mainStore = useMainStore();
	const LoginStore = useLoginStore();
	const themeStore = useThemeStore(); // 主题
	const { theme } = storeToRefs(themeStore);
	const themeColor = ref(themeStore.theme == 'theme-blue' ? '#02B7E6' : '#FF6430')
	
	const scrollWidth = ref(uni.getSystemInfoSync().windowWidth - 20 + 'px');
	const scrollHeight = ref(uni.getSystemInfoSync().windowHeight + 'px');
	const statusBarHeight = ref(uni.getSystemInfoSync().statusBarHeight);
	const tabStyle = ref({ justifyContent: 'space-around'});
	const industryTabIndex = ref(0);
	const searchValue = ref('');
	const triggered = ref(false);
	const dataList = ref([]);
	const tabData = ref([{name:'未读'},{name:'已读'},{name:'全部'}]);
	const tabData2 = ref([{name:'草稿箱'},{name:'发件箱'}]);
	const PageSize = ref(10);
	const approveSearch = ref(null);
	const selectTime = ref('全部');
	const timeList = ref([{
		text: '全部',
		value: '全部',
		dateRang: ['', '']
	},{
		text: "今天",
		value: "今天",
		dateRang: dateRangUtil.getLastToday()
	},{
		text: "昨天",
		value: "昨天",
		dateRang: dateRangUtil.getYesterday()
	},{
		text: "本周",
		value: "本周",
		dateRang: dateRangUtil.getCurrentWeek()
	},{
		text: "上周",
		value: "上周",
		dateRang: dateRangUtil.getLastWeek()
	},{
		text: "近三天",
		value: "近三天",
		dateRang: dateRangUtil.getLast3Day()
	},{
		text: "本月",
		value: "本月",
		dateRang: dateRangUtil.getCurrentMonth()
	},{
		text: "上月",
		value: "上月",
		dateRang: dateRangUtil.getLastMonth()
	},{
		text: "自定义",
		value: "自定义",
		dateRang: "自定义"
	}]);
	const StartDt = ref('');
	const EndDt = ref('');
	const pageList1 = ref({
		CurrentPage: 1, //第几页
		RowsCount: 0, //总条数
		PageCount: 1, //总页数
		data: [],
		cTime: '',
		c_selectTime: '全部',
		c_selectStatus: '否',
		c_selectType: '收件箱',
		c_selectType2: '草稿箱',
		c_s: '',
		c_e: '',
	})
	const pageList2 = ref({
		CurrentPage: 1, //第几页
		RowsCount: 0, //总条数
		PageCount: 1, //总页数
		data: [],
		cTime: '',
		c_selectTime: '全部',
		c_selectStatus: '是',
		c_selectType: '收件箱',
		c_selectType2: '发件箱',
		c_s: '',
		c_e: '',
	})
	const pageList3 = ref({
		CurrentPage: 1, //第几页
		RowsCount: 0, //总条数
		PageCount: 1, //总页数
		data: [],
		cTime: '',
		c_selectTime: '全部',
		c_selectStatus: '',
		c_selectType: '收件箱',
		c_s: '',
		c_e: '',
	})
	const isTypeShow = ref(false);
	const selType = ref('收件箱');
	
	const onTapLeft = () =>{
		uni.navigateBack();
	}
	const selStoreById =()=>{
		switch (industryTabIndex.value){
			case 0:
				pageList1.value.CurrentPage = 1;
				pageList1.value.data = [];
				onRefresh();
				break;
			case 1:
				pageList2.value.CurrentPage = 1;
				pageList2.value.data = [];
				onRefresh();
				break;
			case 2:
				pageList3.value.CurrentPage = 1;
				pageList3.value.data = [];
				onRefresh();
				break;
			default:
				break;
		}
	}
	const buttonClickTime = (e)=>{
		if(e.modelType=='StartDt'){
			selectTime.value='自定义';
			StartDt.value = e.modelValue;
		}else if(e.modelType=='EndDt'){
			selectTime.value='自定义';
			EndDt.value = e.modelValue;
		}else{
			selectTime.value=e.modelType;
		}
	}
	const CancelCondition = () =>{
		switch (industryTabIndex.value) {
			case 0:
				selectTime.value = '全部';
				pageList1.value.c_selectTime = '全部';
				pageList1.value.c_s = '';
				pageList1.value.c_e = '';
				break;
			case 1:
				selectTime.value = '全部';
				pageList2.value.c_selectTime = '全部';
				pageList2.value.c_s = '';
				pageList2.value.c_e = '';
				break;
			case 2:
				selectTime.value = '全部';
				pageList3.value.c_selectTime = '全部';
				pageList3.value.c_s = '';
				pageList3.value.c_e = '';
				break;
		}
		StartDt.value = '';
		EndDt.value = '';
	}
	const ConfirmCondition = () =>{
		if(selectTime.value=='自定义'){
			if(!StartDt.value||!EndDt.value){
				uni.showToast({
					duration: 3500,
					icon: 'none',
					title: '请选择开始日期、结束日期!',
				});
				return false;
			}
		}else{
			StartDt.value = '';
			EndDt.value = '';
		}
		approveSearch.value.closeDrawer();
		switch (industryTabIndex.value){
			case 0:
				pageList1.value.CurrentPage = 1;
				pageList1.value.data = [];
				pageList1.value.c_selectTime=selectTime.value;
				pageList1.value.c_s = StartDt.value;
				pageList1.value.c_e = EndDt.value;
				QueryEMails();
				break;
			case 1:
				pageList2.value.CurrentPage = 1;
				pageList2.value.data = [];
				pageList2.value.c_selectTime=selectTime.value;
				pageList2.value.c_s = StartDt.value;
				pageList2.value.c_e = EndDt.value;
				QueryEMails();
				break;
			case 2:
				pageList3.value.CurrentPage = 1;
				pageList3.value.data = [];
				pageList3.value.c_selectTime=selectTime.value;
				pageList3.value.c_s = StartDt.value;
				pageList3.value.c_e = EndDt.value;
				QueryEMails();
				break;
			default:
				break;
		}
	}
	const tabChange = (e) =>{
		switch (e) {
			case 0:
				selectTime.value = pageList1.value.c_selectTime;
				StartDt.value = pageList1.value.c_s;
				EndDt.value = pageList1.value.c_e;
				break;
			case 1:
				selectTime.value = pageList2.value.c_selectTime;
				StartDt.value = pageList2.value.c_s;
				EndDt.value = pageList2.value.c_e;
				break;
			case 2:
				selectTime.value = pageList3.value.c_selectTime;
				StartDt.value = pageList3.value.c_s;
				EndDt.value = pageList3.value.c_e;
				break;
		}
		if (industryTabIndex.value !== e) {
			industryTabIndex.value = e;
			switch (e){
				case 0:
					if (pageList1.value.cTime) {
						let minute = 0;
						minute = Math.floor((new Date() - pageList1.value.cTime) / (60 * 1000))
						console.log("上次查询距现在相差分钟数：" + minute)
						if (minute >= 1) {
							pageList1.value.CurrentPage = 1;
							pageList1.value.data = [];
							QueryEMails();
						} else {
							dataList.value = pageList1.value.data;
						}
					} else {
						pageList1.value.CurrentPage = 1;
						pageList1.value.data = [];
						QueryEMails();
					}
					break;
				case 1:
					if (pageList2.value.cTime) {
						let minute = 0;
						minute = Math.floor((new Date() - pageList2.value.cTime) / (60 * 1000))
						console.log("上次查询距现在相差分钟数：" + minute)
						if (minute >= 1) {
							pageList2.value.CurrentPage = 1;
							pageList2.value.data = [];
							QueryEMails();
						} else {
							dataList.value = pageList2.value.data;
						}
					} else {
						pageList2.value.CurrentPage = 1;
						pageList2.value.data = [];
						QueryEMails();
					}
					break;
				case 2:
					if (pageList3.value.cTime) {
						let minute = 0;
						minute = Math.floor((new Date() - pageList3.value.cTime) / (60 * 1000))
						console.log("上次查询距现在相差分钟数：" + minute)
						if (minute >= 1) {
							pageList3.value.CurrentPage = 1;
							pageList3.value.data = [];
							QueryEMails();
						} else {
							dataList.value = pageList3.value.data;
						}
					} else {
						pageList3.value.CurrentPage = 1;
						pageList3.value.data = [];
						QueryEMails();
					}
					break;
				default:
					break;
			}
		}
	}
	// 下拉刷新
	const onRefresh = ()=>{
		if (triggered.value) {
			return false;
		};
		triggered.value = true;
		switch (industryTabIndex.value) {
			case 0:
				pageList1.value.CurrentPage = 1;
				pageList1.value.data = [];
				QueryEMails();
				break;
			case 1:
				pageList2.value.CurrentPage = 1;
				pageList2.value.data = [];
				QueryEMails();
				break;
			case 2:
				pageList3.value.CurrentPage = 1;
				pageList3.value.data = [];
				QueryEMails();
				break;
		}
		setTimeout(() => {
			triggered.value = false;
		}, 1000)
	}
	// 加载更多
	const templateLower = ()=>{
		switch (industryTabIndex.value) {
			case 0:
				if (pageList1.value.CurrentPage < pageList1.value.PageCount) {
					pageList1.value.CurrentPage = pageList1.value.CurrentPage + 1;
					QueryEMails();
				}
				break;
			case 1:
				if (pageList2.value.CurrentPage < pageList2.value.PageCount) {
					pageList2.value.CurrentPage = pageList2.value.CurrentPage + 1;
					QueryEMails();
				}
				break;
			case 2:
				if (pageList3.value.CurrentPage < pageList3.value.PageCount) {
					pageList3.value.CurrentPage = pageList3.value.CurrentPage + 1;
					QueryEMails();
				}
				break;
		}
	}
	const setUserPic = e =>{
		let pic = '';
		const imgUrl = LoginStore.EnjoyMain.replace('/Enjoy/Service', '');
		pic = imgUrl + '/File/DownLoadImage/' + e;
		return pic
	}
	const QueryEMails = () =>{
		service.enjoyShowLoading('正在加载...');
		let page = {};
		switch (industryTabIndex.value){
			case 0:
				page = JSON.parse(JSON.stringify(pageList1.value));
				break;
			case 1:
				page= JSON.parse(JSON.stringify(pageList2.value));
				break;
			case 2:
				page= JSON.parse(JSON.stringify(pageList3.value));
				break;
			default:
				break;
		}
		let st = '';
		let en = '';
		if(page.c_selectTime=='自定义'){
			st = page.c_s;
			en = page.c_e;
		} else if (page.c_selectTime=='全部'){
			st = '';
			en = '';
		} else {
			let list = timeList.value.filter(item => item.value==page.c_selectTime);
			if(list.length>0){
				st = list[0].dateRang[0];
				en = page.c_selectTime=='上周'?list[0].dateRang[2]:list[0].dateRang[1];
			}
		}
		let request = {
		    url: LoginStore.EnjoyMain,
		    data: {
		        UniqueKey: "管易通40内部邮件",
		        ObjectData: {
					IsNotPage: false,
					PageSize: PageSize.value,
					Sql: null,
					c_type: selType.value=='收件箱'?page.c_selectType:page.c_selectType2,
					c_sender:mainStore.loginInfo.sUser,
					c_read_status: selType.value=='收件箱'?page.c_selectStatus:null,
					c_title:searchValue.value,
					
					c_send_start_dt:selType.value=='收件箱'?st:null,
					c_send_end_dt:selType.value=='收件箱'?en:null,
					
					c_mk_start_dt: selType.value=='发件箱'?st:null,
					c_mk_end_dt: selType.value=='发件箱'?en:null,
					
					CurrentPage:page.CurrentPage
				},
		        MethodName: "QueryEMails",
		    },
		}
		service.request(request, (res) => {
		    if (res && res.data) {
		        if (!res.data.HasException) {
					const ObjectData = res.data.ObjectData;
					page.RowsCount = ObjectData.RowsCount;
					page.PageCount = ObjectData.PageCount;
					page.CurrentPage = ObjectData.CurrentPage;
					page.cTime = new Date();
					if (ObjectData.CurrentPage === 1) {
						page.data = []
					}
					for (let i = 0; i < ObjectData.ReturnObject.length; i++) {
						page.data.push({
							...ObjectData.ReturnObject[i],
							c_send_dt:dateRangUtil.formatDate(ObjectData.ReturnObject[i].c_send_dt,'MM-DD'),
							c_sender_pic:setUserPic(ObjectData.ReturnObject[i].c_sender),
							selType:selType.value,
							industryTabIndex:industryTabIndex.value
						})
					}
					dataList.value = page.data;
					switch (industryTabIndex.value){
						case 0:
							pageList1.value = page;
							break;
						case 1:
							pageList2.value = page;
							break;
						case 2:
							pageList3.value = page;
							break;
						default:
							break;
					}
		        } else {
		            service.enjoyShowToast(res.data.Exception.Message)
		        }
		    }
			service.enjoyHideLoading();
		}, () => {
			service.enjoyHideLoading();
		    console.log('失败')
		});
	}
	const TypeChange = () =>{
		isTypeShow.value = !isTypeShow.value;
	}
	const openWriteEmail = () =>{
		uni.navigateTo({
			url: './WriteEmail'
		});
	}
	const TypeEMailsQuery = e =>{
		selType.value = e;
		pageList1.value.CurrentPage = 1;
		pageList1.value.data = [];
		pageList1.value.cTime = '';
		pageList1.value.c_selectTime = '全部';
		pageList1.value.c_s = '';
		pageList1.value.c_e = '';
		
		pageList2.value.CurrentPage = 1;
		pageList2.value.data = [];
		pageList2.value.cTime = '';
		pageList2.value.c_selectTime = '全部';
		pageList2.value.c_s = '';
		pageList2.value.c_e = '';
		
		pageList3.value.CurrentPage = 1;
		pageList3.value.data = [];
		pageList3.value.cTime = '';
		pageList3.value.c_selectTime = '全部';
		pageList3.value.c_s = '';
		pageList3.value.c_e = '';
		
		industryTabIndex.value = e== '收件箱' ? 2 : 0 ;
		
		onRefresh();
		TypeChange();
	}
	onReady(()=>{
		uni.getSystemInfo({
			success: function(res) {
				const userInfoPage = uni.createSelectorQuery().select(".content-img");
				userInfoPage.boundingClientRect(function(data) {
					scrollHeight.value = (res.windowHeight - data.height - 20)+'px';
				}).exec()
			}
		});
	})
	onLoad(()=>{
		QueryEMails();
	})
	defineExpose({
		onRefresh
	})
</script>

<style lang="scss" scoped>
	@import '@/main.scss';

	.content-img {
		background-color: #FFFFFF;
		background-repeat: no-repeat;
		width: 100%;
	}

	.main-view {
		flex: 1;
		flex-direction: column;
		padding: 20rpx;
		background-color: #f2f2f2;
	}

	.approve-list {
		padding: 28rpx 0rpx 24rpx 0rpx;
		border-radius: 20rpx;
		background-color: #fff;
	}

	.flex {
		display: flex;
	}

	.flex-1 {
		flex: 1;
	}

	.flex-direction-column {
		flex-direction: column !important;
	}

	.font-size-24 {
		font-size: 24rpx;
	}

	.font-size-26 {
		font-size: 26rpx;
	}

	.font-size-28 {
		font-size: 28rpx;
	}

	.font-size-32 {
		font-size: 32rpx;
	}

	.font-weight-bold {
		font-weight: bold;
	}

	.margin-top-16 {
		margin-top: 16rpx;
	}

	.margin-right-16 {
		margin-right: 16rpx;
	}

	.margin-bottom-20 {
		margin-bottom: 20rpx;
	}

	.padding-bottom-20 {
		padding-bottom: 20rpx;
	}

	.padding-left-28 {
		padding-left: 28rpx;
	}

	.padding-right-28 {
		padding-right: 28rpx;
	}

	.justify-content-space-between {
		justify-content: space-between;
	}

	.justify-content-flex-end {
		justify-content: flex-end;
	}

	.justify-content-center {
		justify-content: center;
	}

	.align-items-center {
		align-items: center !important;
	}

	.color-888 {
		color: rgba(136, 136, 136, 1);
	}

	.color-FF4000 {
		color: rgba(255, 64, 0, 1);
	}

	.color-02B7E6 {
		color: rgba(2, 183, 230, 1);
	}

	.border-bottom-eee {
		border-bottom: solid 1px rgba(238, 238, 238, 1);
	}

	.approve-mark {
		font-size: 26rpx;
		padding: 1px 7px;
		background-color: RGBA(242, 251, 254, 1);
		border-radius: 18px;
	}

	.search-fields {
		width: 100%;
		background: #FFFFFF;

		.center {
			padding-bottom: 22rpx;
		}

		.bottom {
			background: #ffffff;
			border-top: 1rpx solid $uni-line-color;
			display: flex;
			justify-content: center;
			padding: 20rpx;
		}
	}

	.date-defined {
		padding-left: 185rpx;
		padding-top: 20rpx;
		padding-bottom: 20rpx;
		font-size: 14px;
	}

	.word-wrap-break-word {
		word-wrap: break-word;
	}

	.header-content {
		height: 88rpx;
		padding: 0 6px;
		background-color: #fff;
		align-items: center;
		position: relative;
		z-index: 2;
	}

	.email-option {
		position: fixed;
		background-color: rgb(255, 255, 255);
		z-index: 2;
		top: 44px;
		left: 0px;
		right: 0px;
		height: 176rpx;
	}

	.email-mask {
		position: fixed;
		z-index: 1;
		top: 0;
		right: 0;
		left: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
	}

	.padding-left-28 {
		padding-left: 28rpx;
	}

	.padding-right-28 {
		padding-right: 28rpx;
	}

	.border-bottom-eee {
		border-bottom: solid 1px rgba(238, 238, 238, 1);
	}

	.iconfont {
		font-size: 20px;
		width: 40px;
		height: 100%;
		text-align: center;
		line-height: 37px;
		@include themeText("themeText");
	}

	.email-edit {
		width: 76rpx;
		height: 76rpx;
		background: var(--theme-bgc-color);
		border-radius: 50%;
		position: fixed;
		bottom: 40rpx;
		right: 28rpx;
	}
	.bottom-bg {
		height: 40px;
		border-radius: 20px;
	}
	
	.button-theme {
		background: var(--theme-bgc-color);
	}
</style>